<template>
  <div class="op-group comp-op-common">
    <div class="op-title">数组解析</div>
    <div class="option-item">
      <div v-if="!isShowSub" class="title-row fixed">
        <span class="label">解析数组中所有的值成新列</span>
        <div>
          <a-button class="op-btn" type="primary" size="small" @click="doAction"
            >确定</a-button
          >
          <a-button class="op-btn" size="small" @click="showDetail"
            >编辑</a-button
          >
        </div>
      </div>
      <div v-if="isShowSub" class="detail-panel">
        <div class="sub-item">
          <span class="check-item">解析数组中所选位置对应的值成新列</span>
          <div class="select-content">
            <div
              v-for="indexItem in arrayIndexOptions"
              :key="indexItem.index1"
              class="index-item"
            >
              <a-checkbox
                size="small"
                :checked="indexItem.check"
                @change="onSelectArrayIndex($event, indexItem)"
              >
                {{ indexItem.text }}
              </a-checkbox>
              <span>新列名</span>
              <a-input
                v-model="indexItem.newColumnName"
                size="small"
                style="width: 260px;"
                placeholder="请输入"
              />
            </div>
          </div>
        </div>

        <div class="button-row">
          <a-button class="op-btn-sub" size="small" @click="cancel"
            >取消</a-button
          >
          <a-button
            class="op-btn-sub"
            type="primary"
            size="small"
            @click="doOption"
            >确定</a-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
/**
 * 整列选择 智能推荐 数组解析
 * @author Hou Jinhui
 */
import { Component, Prop, Vue } from 'vue-property-decorator'
import { apiGetJsonKeysOrArrayIndex } from '@/api/data-clean'
import DataStore, { OptionPreViewAction } from '@/store/modules/dataview'

interface IIndexOption {
  check: boolean
  index1: number
  text: number
  newColumnName: string
}

@Component({
  components: {},
})
export default class ColumnArrayParse extends Vue {
  @Prop({ type: String, default: '' }) tableName!: String | undefined

  //  是否进入编辑模式
  private isShowSub: boolean = false
  private arrayIndexOptions: IIndexOption[] = [] // 选择项

  // 所选列列名
  public get selectedColumnName() {
    return DataStore.tableSelectColumns[0].name
  }

  mounted() {
    this.getArrayIndexOptions()
  }

  /**
   * 获取 array 列所有 index 索引
   * @param parameters
   * @private
   */
  private async getArrayIndexOptions(parameters?: any) {
    const requestParameters = {
      col: this.selectedColumnName,
      type: 'array',
      table: this.tableName,
    }
    // 更新 key options
    const response = await apiGetJsonKeysOrArrayIndex({
      data: {
        ...requestParameters,
        ...parameters,
      },
    })
    if (!response.data.success) {
      this.$message.error(response.data.message)
      return
    }
    const { result } = response.data
    this.arrayIndexOptions = result.index.map((item: number) => {
      return {
        check: true,
        index1: item, // 后端给的索引
        text: item + 1,
        newColumnName: `${this.selectedColumnName}_${item + 1}`,
      }
    })
  }

  /**
   * 修改 array index 选择状态
   * @param $event
   * @param indexItem 索引项
   */
  public onSelectArrayIndex($event: any, indexItem: any) {
    const { checked } = $event.target
    indexItem.check = checked
  }

  //  点击取消，关闭推荐面板
  public cancel() {
    this.arrayIndexOptions.forEach((item: any) => {
      item.check = true
    })
    this.isShowSub = false
  }

  public showDetail() {
    this.isShowSub = true
  }

  /**
   * 编辑确认
   */
  public doOption() {
    this.doAction()
  }

  /**
   * 根据 arrayIndexOptions 要解析的索引
   */
  public get newColumns(): IIndexOption[] {
    const { arrayIndexOptions } = this
    return arrayIndexOptions.filter((option: any) => option.check)
  }

  /**
   * 根据 arrayIndexOptions 获取要解析的索引
   */
  public get newColumnIndex(): number[] {
    const { arrayIndexOptions } = this
    return arrayIndexOptions
      .filter((option: any) => option.check)
      .map((item: any) => item.index1)
  }

  /**
   * 检查列名重复
   */
  public columnNamesIsRepeat(columnNames: string[]) {
    const hash: any = {}
    let repeat: boolean = false
    columnNames.forEach((item: any) => {
      if (hash[item]) {
        repeat = true
      }
      hash[item] = true
    })
    return repeat
  }

  /**
   *  确认
   */
  public doAction() {
    const selectIndexOptions: IIndexOption[] = this.newColumns
    const newColumnsName: string[] = selectIndexOptions.map(
      (item: any) => item.newColumnName
    )
    if (this.columnNamesIsRepeat(newColumnsName)) {
      this.$message.warn('存在新列名重复，请确认！')
      return
    }
    const haveEmptyName: boolean = newColumnsName.some(
      (name: string) => name.trim() === ''
    )
    if (haveEmptyName) {
      this.$message.warn('新列名不能为空，请确认！')
      return
    }
    const selectIndex: any[] = selectIndexOptions.map(
      (item: any) => item.index1
    )
    const actionInfo: any = {
      action: OptionPreViewAction.selectionArrayParse,
      desc: '选择列 > 对象解析',
      col: this.selectedColumnName,
      data: {
        index: selectIndex,
        newCol: newColumnsName,
      },
    }
    this.$emit('actiondone', {
      ...actionInfo,
    })
  }
}
</script>

<style lang="less" scoped>
@import url('../op.less');

.select-content {
  max-height: 150px;
  overflow-y: auto;
  padding: 12px 0 0 2px;
  width: 100%;

  .index-item {
    align-items: center;
    display: flex;
    height: 32px;
    justify-content: space-between;
  }
}
</style>
